package cn.xutongxue.user.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.xutongxue.common.entity.DeleteRequest;
import cn.xutongxue.common.entity.ResponseResult;
import cn.xutongxue.common.enums.Errors;
import cn.xutongxue.common.excption.BusinessException;
import cn.xutongxue.user.entity.User;
import cn.xutongxue.user.module.dto.LoginDto;
import cn.xutongxue.user.module.dto.RegisterDto;
import cn.xutongxue.user.module.dto.UserQueryParamsDto;
import cn.xutongxue.user.module.vo.TokenVo;
import cn.xutongxue.user.module.vo.UserVo;
import cn.xutongxue.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 用户模块接口
 */
@RequestMapping("/user")
@RestController
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    /**
     * 注册
     *
     * @param registerDto
     * @return
     */
    @PostMapping("/register")
    public ResponseResult<Boolean> register(@RequestBody RegisterDto registerDto) {
        // 判断参数是否为空
        if (StringUtils.isAllBlank(registerDto.getUsername(), registerDto.getPassword())) {
            return ResponseResult.error(Errors.PARAMS_ERROR);
        }
        return userService.register(registerDto);
    }

    /**
     * 登录
     *
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public ResponseResult<TokenVo> login(@RequestBody LoginDto loginDTO) {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();

        // 判断参数是否为空
        if (StringUtils.isAllBlank(username, password)) {
            return ResponseResult.error(Errors.PARAMS_ERROR);
        }

        // 加密密码
        String encryptPassword = SaSecureUtil.md5(password);
        // 查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username)
                .eq(User::getPassword, encryptPassword);

        // 判断用户是否存在
        User loginUser = userService.getOne(wrapper);
        if (loginUser == null) {
            return ResponseResult.error(Errors.USERNAME_OR_PASSWORD_ERROR);
        }
        // 登录
        StpUtil.login(loginUser.getId());
        // 生成token
        String token = StpUtil.getTokenValue();
        return ResponseResult.success(new TokenVo(token));
    }

    /**
     * 退出登录
     *
     * @return
     */
    @GetMapping("/logout")
    public ResponseResult<Boolean> logout() {
        StpUtil.logout();
        return ResponseResult.success(true);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("/info")
    public ResponseResult<UserVo> info() {
        int currentLoginUserId = StpUtil.getLoginIdAsInt();
        User user = userService.getById(currentLoginUserId);
        if (user == null) {
            throw new BusinessException(Errors.NOT_LOGIN_ERROR);
        }
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user, userVo);
        return ResponseResult.success(userVo);
    }


    // region 管理员功能

    /**
     * 获取用户列表
     * @return
     */
    @PostMapping("/list")
    public ResponseResult<Page<UserVo>> list(@RequestBody UserQueryParamsDto userQueryParams) {
        if (userQueryParams == null) {
            throw new BusinessException(Errors.PARAMS_ERROR);
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.isNoneBlank(userQueryParams.getUsername()), User::getUsername, userQueryParams.getUsername())
                .eq(StringUtils.isNoneBlank(userQueryParams.getNickname()), User::getNickname, userQueryParams.getNickname())
        ;
        // 分页获取
        Page<User> page = userService.page(new Page<>(userQueryParams.getCurrent(), userQueryParams.getSize()), wrapper);
        // 重新封装page
        Page<UserVo> userVoPage = new Page<>();
        BeanUtil.copyProperties(page, userVoPage);
        return ResponseResult.success(userVoPage);
    }

    @PostMapping("/remove")
    public ResponseResult<Boolean> remove(@RequestBody DeleteRequest deleteRequest)  {
        if (deleteRequest == null) {
            throw new BusinessException(Errors.PARAMS_ERROR);
        }
        boolean result = userService.removeById(deleteRequest.getId());
        return ResponseResult.success(result);
    }


    // endregion


    /**
     * 获取根据ID获取用户角色
     * @param userId
     * @return
     */
    @GetMapping("/getUserRoleById")
    public String getUserRole(@RequestParam("userId") Integer userId) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(Errors.NOT_LOGIN_ERROR);
        }
        return user.getUserRole();
    }

    /**
     * 根据用户id获取用户信息
     * @param userId
     * @return
     */
    @GetMapping("/getUserInfoById")
    public UserVo getUserInfo(@RequestParam("userId") Integer userId) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(Errors.NOT_LOGIN_ERROR);
        }
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(user, userVo);
        return userVo;
    }
}
